from typing import Optional
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(-1)
        cur = dummy
        while list1 and list2:
            if list1.val <= list2.val:
                cur.next = list1
                list1 = list1.next
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
        cur.next = list1 if list1 else list2
        return dummy.next
# 测试代码（可选）
if __name__ == "__main__":
    # 构造链表 list1: 1 -> 2 -> 4
    list1 = ListNode(1, ListNode(2, ListNode(4)))
    # 构造链表 list2: 1 -> 3 -> 4
    list2 = ListNode(1, ListNode(3, ListNode(4)))
    solution = Solution()
    merged = solution.mergeTwoLists(list1, list2)
    # 打印合并后的链表值
    while merged:
        print(merged.val, end=" ")
        merged = merged.next